﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using AccessControl.FingerPrintLibrary;
using AccessControl.HardwareLibrary.EnumAndStruct;
using AccessControl.HardwareLibrary.FS84;
using DevExpress.XtraEditors;


namespace ACTest.FS84Test{
    public partial class MainForm : XtraForm{
        private FS84Communicator FS84;

        private byte[] rawImage;
        private byte[] sample;

        private byte[] currentTemplate, previousTemplate;

        public MainForm(){
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e){

            bool isConnected;
            do{
                FS84 = new FS84Communicator{EnableIdleOptimization = true};
                isConnected = FS84.Connect("192.168.0.231", 5001, 2);
                FS84.FingerPrintDetected += FS84_fingerDetected;
                FS84.WaitTimeoutExpired += FS84_WaitTimeoutExpired;
                //FS84.SetLogFile("D:\\MyProjects\\NewsudProjects\\Related\\log.txt");
            } while (!isConnected);

        }

        private void btnCheckFinger_Click(object sender, EventArgs e){
            int contrast;

            lblIsFinger.Text = FS84.CheckFinger(out contrast) ? "YES, Contrast:" + contrast : "NO";
        }

        private void radioBuzzer_SelectedIndexChanged(object sender, EventArgs e){
            bool DoorSensor0, DoorSensor1;
            FS84.SwitchDevicePeripheral(DevicePeripherals.Buzzer, (bool) radioBuzzer.EditValue, out DoorSensor0,
                                        out DoorSensor1);
            lblDoorSensor0.Text = "Door sensor 0: " + (DoorSensor0 ? "On" : "Off");
            lblDoorSensor1.Text = "Door sensor 1: " + (DoorSensor1 ? "On" : "Off");
        }

        private void radioLock_SelectedIndexChanged(object sender, EventArgs e){
            bool DoorSensor0, DoorSensor1;
            FS84.SwitchDevicePeripheral(DevicePeripherals.LockOn, (bool) radioLock.EditValue, out DoorSensor0,
                                        out DoorSensor1);
            lblDoorSensor0.Text = "Door sensor 0: " + (DoorSensor0 ? "On" : "Off");
            lblDoorSensor1.Text = "Door sensor 1: " + (DoorSensor1 ? "On" : "Off");
        }

        private void radioLED1_SelectedIndexChanged(object sender, EventArgs e){
            bool DoorSensor0, DoorSensor1;
            FS84.SwitchDevicePeripheral(DevicePeripherals.LED1, (bool) radioLED1.EditValue, out DoorSensor0,
                                        out DoorSensor1);
            lblDoorSensor0.Text = "Door sensor 0: " + (DoorSensor0 ? "On" : "Off");
            lblDoorSensor1.Text = "Door sensor 1: " + (DoorSensor1 ? "On" : "Off");
        }

        private void radioLED2_SelectedIndexChanged(object sender, EventArgs e){
            bool DoorSensor0, DoorSensor1;
            FS84.SwitchDevicePeripheral(DevicePeripherals.LED2, (bool) radioLED2.EditValue, out DoorSensor0,
                                        out DoorSensor1);
            lblDoorSensor0.Text = "Door sensor 0: " + (DoorSensor0 ? "On" : "Off");
            lblDoorSensor1.Text = "Door sensor 1: " + (DoorSensor1 ? "On" : "Off");
        }

        private void btnBeep_Click(object sender, EventArgs e){
            FS84.Beep((Beeps) radioBeepTypes.EditValue);
        }

        private void btnCapture_Click(object sender, EventArgs e){
            int contrast, whitePixels;
            byte dosage;

            rawImage = FS84.CaptureAndDownloadImage(false, out contrast, out whitePixels, out dosage);
            Bitmap bitmap =Extraction.GetInstance().CreateImage(rawImage);
            picFinger.BackColor = Color.LightGreen;
            picFinger.Image = bitmap;
        }

        private void FS84_fingerDetected(object sender, FingerPrintDetectedEventArgs args){
            var bitmap = Extraction.GetInstance().CreateImage(args.rawImage);

            picFinger.BackColor = Color.LightGreen;
            picFinger.Image = bitmap;

            FS84.ProcessCapturedSample();
            sample = FS84.DownloadCurrentSample();

            Invoke(
                new MethodInvoker(
                    delegate{
                        lblIsFinger.Text = "Dosage: " + args.dosage + ", C=" + args.contrast + ", W=" + args.whitePixels;

                        if (chkSaveBitmap.Checked){
                            Directory.CreateDirectory(txtSavePath.Text);
                            var fileName = txtSavePath.Text.TrimEnd('\\') + '\\' +
                                              DateTime.Now.ToFileTime() + "_C" + args.contrast + "_W" +
                                              args.whitePixels;
                            bitmap.Save(fileName + ".bmp");
                            var sw = new FileStream(fileName + ".dat", FileMode.Create);
                            sw.Write(sample, 0, sample.Length);
                            sw.Close();
                        }
                        int G;
                        string errorMessage;
                        previousTemplate = currentTemplate;
                        int score=0;

                        var template = Extraction.GetInstance().ExtractToByte(args.rawImage, out G, out errorMessage);
                        if(errorMessage==null){
                            currentTemplate = template;
                            if (previousTemplate != null) score = Verification.GetInstance().Verify(currentTemplate, previousTemplate);
                            MessageBox.Show("Current template G=" + G + " , MatchingScore=" + score);
                        }
                    }));



            if (chkbtnWaitForFinger.Checked) FS84.WaitForFingerprint(0);
        }

        private void chkbtnWaitForFinger_CheckedChanged(object sender, EventArgs e){
            if (chkbtnWaitForFinger.Checked)
                FS84.WaitForFingerprint(0);
            else
                FS84.StopWaitingForFinger();
        }

        private void FS84_WaitTimeoutExpired(object sender, EventArgs e){
            Invoke(new MethodInvoker(delegate { chkbtnWaitForFinger.Checked = false; }));
        }

        private void btnCancel_Click(object sender, EventArgs e){
            FS84.CancelCommand();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e){
            FS84.StopWaitingForFinger();
        }

        private void chkSaveBitmap_CheckedChanged(object sender, EventArgs e){
            txtSavePath.Enabled = chkSaveBitmap.Checked;
        }

        private void btnReboot_Click(object sender, EventArgs e){
            FS84.Reboot();
        }

        private void btnFreeMemory_Click(object sender, EventArgs e){
            MessageBox.Show(FS84.GetFreeMemory().ToString());
        }

        private void btnClearMemory_Click(object sender, EventArgs e){
            FS84.EraseAllTemplates();
        }

    }
}